//
//  HelloWorldLayer.m
//  demo_3
//
//  Created by mac on 12-2-20.
//  Copyright __MyCompanyName__ 2012年. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"
#import "CCTouchDispatcher.h"
#import "SimpleAudioEngine.h"

// HelloWorldLayer implementation
@implementation HelloWorldLayer
//CCSprite *flyFlour;

+(id) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];
    
    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];
    //NGSScoreListBoard *board = [NGSScoreListBoard node];
    
    // add layer as a child to scene
    [scene addChild: layer];
    
    // return the scene
    return scene;
}

-(void)setNumber
{
    _number = [[NSMutableArray alloc] init];
   // NSMutableArray *MutableArray = ［NSMutableArray alloc] init];
    CCSprite *number_1 = [CCSprite spriteWithFile:@"count_01_2x.png"];
    [_number addObject:number_1];
    
    CCSprite *number_2 = [CCSprite spriteWithFile:@"count_02_2x.png"];
    [_number addObject:number_2];
    
    CCSprite *number_3 = [CCSprite spriteWithFile:@"count_03_2x.png"];
    [_number addObject:number_3];
    
    CCSprite *number_4 = [CCSprite spriteWithFile:@"count_04_2x.png"];
    [_number addObject:number_4];
    
    CCSprite *number_5 = [CCSprite spriteWithFile:@"count_05_2x.png"];
    [_number addObject:number_5];
    
    CCSprite *number_6 = [CCSprite spriteWithFile:@"count_06_2x.png"];
    [_number addObject:number_6];
    
    CCSprite *number_7 = [CCSprite spriteWithFile:@"count_07_2x.png"];
    [_number addObject:number_7];
    
    CCSprite *number_8 = [CCSprite spriteWithFile:@"count_08_2x.png"];
    [_number addObject:number_8];
    
    CCSprite *number_9 = [CCSprite spriteWithFile:@"count_09_2x.png"];
    [_number addObject:number_9];
    
    CCSprite *number_10 = [CCSprite spriteWithFile:@"count_10_2x.png"];
    [_number addObject:number_10];
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {
        winSize = [[CCDirector sharedDirector] winSize];
        
        //invoke init method defined by @cc
        [self initExtension];
        winSize = [[CCDirector sharedDirector] winSize];
        foodIndex=FLOUR_INDEX;
        distance_betweenFood=150;
        realDest = ccp(winSize.width/2, 330);
        oneSlice = true;
        [self setPoints];
        [self addFlour];
        [self addKnife];
        [self addMutton];
        [self addBowl];
        [self setNumber];
        [self addBeef];
        [self addRadish];
        [self addCucumber];
        
        //add the score list board onto the main layer
        [self addScoreListBoard];
        [self addBackgoundLayer];
        
        middle_area=flour.boundingBox;
        //[self loadBgMusic];
        //[self playBgMusic: @"signal waltz.wma"];
        [CDAudioManager sharedManager].backgroundMusic.volume = 1.0f;
        //[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"sw.mp3"];
        
        self.isTouchEnabled = YES;
        _numberOfFlour=0;
        //[self schedule:@selector(nextBlow:)];
    }	return self;
}

-(void) registerWithTouchDispatcher 
{ 
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
}

-(void)gameLogic:(ccTime)dt {
    [self addTarget];
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    //CGPoint touchLocation = [touch locationInView: [touch view]];
    
    CGPoint touchLocation = [touch locationInView: [touch view]];
    temp= [self convertTouchToNodeSpace:touch];
    //temp=[[CCDirector sharedDirector] convertToGL:touchLocation];
    temp_1=temp;
    
    if(CGRectContainsPoint(middle_area, temp_1)){//in middle
        inside=true;
        areaIndex=0;
        knife.position=temp_1;
        oneSlice=true;
        cute=true;
        draw=false;
        //初始化 *片飞行方向的 起始点 终止点 位置
        directionStartPoint = temp;
        directionEndPoint = temp;
    }
    else if (CGRectContainsPoint(Beef.boundingBox, temp_1)) {//in beef
            inside=true;
            areaIndex=BEEF_INDEX;
            offset=temp_1.x-beefPoint.x;
            cute=false;
            draw=true;
        }
    else if (CGRectContainsPoint(Radish.boundingBox, temp_1)) {//in flour
            inside=true;
            areaIndex=RADISH_INDEX;
            offset=temp_1.x-radishPoint.x;
            cute=false;
            draw=true;
    }
    else if (CGRectContainsPoint(flour.boundingBox, temp_1)) {//in flour
            inside=true;
            areaIndex=FLOUR_INDEX;
            offset=temp_1.x-flourPoint.x;
            cute=false;
            draw=true;
            }
    else if (CGRectContainsPoint(Cucumber.boundingBox, temp_1)) {//in flour
            inside=true;
            areaIndex=CUCUMBER_INDEX;
            offset=temp_1.x-cucumberPoint.x;
            cute=false;
            draw=true;
    }
    else if(CGRectContainsPoint(Mutton.boundingBox, temp_1)){//in mutton
            inside=true;
            areaIndex=MUTTON_INDEX;
            offset=temp_1.x-muttonPoint.x;
            cute=false;
            draw=true;
        }
    else{inside=false;}
    
    
    return YES;
}
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [touch locationInView: [touch view]];
    temp_4=[[CCDirector sharedDirector] convertToGL:touchLocation];
    
    if (inside) {
        //更新 *片飞行方向的 起始点 结束点 位置
        directionStartPoint = directionEndPoint;
        directionEndPoint = temp_4;
        
        distance=(temp_4.x-temp_1.x)*(temp_4.x-temp_1.x)+(temp_4.y-temp_1.y)*(temp_4.y-temp_1.y);
        if (areaIndex==0) {//削
            knife.position=temp_4;
            if(CGRectContainsPoint(middle_area, temp_4))
            {
            }
            else if(distance>=500&&oneSlice)
            {
                [self flyOneSlice:foodIndex :temp_4];
                oneSlice=false;
            }
            
        }
        
        else if(areaIndex==BEEF_INDEX)
        {
            [self getAll_x:BEEF_INDEX];
            [self moveSprites];
        }
        else if(areaIndex==RADISH_INDEX)
        {
            [self getAll_x:RADISH_INDEX];
            [self moveSprites];
            
        }
        else if(areaIndex==FLOUR_INDEX)
        {
            [self getAll_x:FLOUR_INDEX];
            [self moveSprites];
        }
        else if(areaIndex==CUCUMBER_INDEX)
        {
            [self getAll_x:CUCUMBER_INDEX];
            [self moveSprites];
        }
        else if(areaIndex==MUTTON_INDEX)
        {
            [self getAll_x:MUTTON_INDEX];
            [self moveSprites];
        }
    }//
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if(inside)
    {//
        CGPoint touchLocation = [touch locationInView: [touch view]];
        temp_2=[[CCDirector sharedDirector] convertToGL:touchLocation];
        if(areaIndex==0&&oneSlice)
        {///
            [self flyOneSlice:foodIndex :temp_2];
        }///
        else
        {
            [self finalLocation:areaIndex :temp_2];
            [self moveToTheFinalLocation];
        }///
        
    }//if
    //////////////
}


-(CGPoint) locationFromTouch:(UITouch*)touch
{
    CGPoint touchLocation = [touch locationInView: [touch view]];
    return [[CCDirector sharedDirector] convertToGL:touchLocation];
}

-(CGRect)AtlasRect:(CCSprite *)atlSpr
{
    CGRect rc = [atlSpr textureRect];
    return CGRectMake( - rc.size.width / 2, -rc.size.height / 2, rc.size.width, rc.size.height); 
}       

-(bool)inOrOut:(CGPoint)point :(CGRect)rect
{
    return  CGRectContainsPoint(rect, point);
}
       
-(void)showNumber:(int)num{
    CCSprite *number = [_number objectAtIndex:num];
    number.scale=0.5;
    number.tag=3;
    [self addChild:number z:NUMBER_Z_INDEX];
    [number runAction:[CCSequence actions:
                           [CCPlace actionWithPosition:ccp(NUMBER_X,NUMBER_Y)],
                           [CCFadeOut actionWithDuration:0.3f],
                       [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                           nil]];
}

-(void)addKnife{
    knife = [CCSprite spriteWithFile:@"knife_2x.png" rect:CGRectMake(0, 0, 524, 226)];
    knife.scale=0.3;
    knife.position = ccp(winSize.width/2,30);
    [self addChild:knife z:KNIFE_LAYER_Z_INDEX];
}

-(void)addBeef{
    Beef = [CCSprite spriteWithFile:@"lBeef_2x.png" rect:CGRectMake(0, 0, BEEF_WIDTH, BEEF_HEIHT)];
    Beef.position=beefPoint;
    Beef.scale=BEEF_SCALE;
    [self addChild:Beef z:BEEF_LAYER_Z_INDEX];
    }

-(void)addFlour{
    flour = [CCSprite spriteWithFile:@"lFlour_2x.png" rect:CGRectMake(0, 0, FLOUR_WIDTH, FLOUR_HEIHT)];
    flour.scale=FLOUR_SCALE;
    flour.position = flourPoint;
    [self addChild:flour z:FLOUR_LAYER_Z_INDEX];
    }

-(void)addMutton{
    Mutton = [CCSprite spriteWithFile:@"lMutton_2x.png" rect:CGRectMake(0, 0, MUTTON_WIDTH, MUTTON_HEIHT)];
    Mutton.position=muttonPoint;
    Mutton.scale=MUTTON_SCALE;
    [self addChild:Mutton z:MUTTON_LAYER_Z_INDEX];
}

-(void)addCucumber{
    Cucumber = [CCSprite spriteWithFile:@"lCucumber_2x.png" rect:CGRectMake(0, 0, CUCUMBER_WIDTH, CUCUMBER_HEIHT)];
    Cucumber.position=cucumberPoint;
    Cucumber.scale=CUCUMBER_SCALE;
    [self addChild:Cucumber z:CUCUMBER_LAYER_Z_INDEX];
}
-(void)addRadish{
    Radish = [CCSprite spriteWithFile:@"lRadish_2x.png" rect:CGRectMake(0, 0, RADISH_WIDTH, RADISH_HEIHT)];
    Radish.position=radishPoint;
    Radish.scale=RADISH_SCALE;
    [self addChild:Radish z:RADISH_LAYER_Z_INDEX];
}

-(void)addFlyBeef:(CGPoint)p{
    flyBeef = [CCSprite spriteWithFile:@"fly_beef_2x.png" rect:CGRectMake(0, 0, FLYBEEF_WIDTH, FLYBEEF_HEIHT)];
    flyBeef.scale=0.4;
    flyBeef.tag=2;
    flyBeef.position=p;
    [self addChild:flyBeef z:FLY_SLICE_LAYER_Z_INDEX];
    //
    [flyBeef runAction:[CCSequence actions:
                        [CCMoveTo actionWithDuration:TIMETOFLY position:realDest],
                        [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                        nil]];
}
-(void)addFlyRadish:(CGPoint)p{
    flyRadish = [CCSprite spriteWithFile:@"fly_radish_2x.png" rect:CGRectMake(0, 0, FLYRADISH_WIDTH, FLYRADISH_HEIHT)];
    flyRadish.scale=0.4;
    flyRadish.tag=2;
    flyRadish.position=p;
    [self addChild:flyRadish z:FLY_SLICE_LAYER_Z_INDEX];
    //
    [flyRadish runAction:[CCSequence actions:
                          [CCMoveTo actionWithDuration:TIMETOFLY position:realDest],
                          [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                          nil]];
}
-(void)addFlyFlour:(CGPoint)p{
    flyFlour = [CCSprite spriteWithFile:@"fly_flour_2x.png" rect:CGRectMake(0, 0, FLYFLOUR_WIDTH, FLYFLOUR_HEIHT)];
    flyFlour.scale=0.4;
    flyFlour.tag=2;
    flyFlour.position=p;
    [self addChild:flyFlour z:FLY_SLICE_LAYER_Z_INDEX];
    
    //面片bezier曲线飞行轨迹代码
    CCAction *action = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
    CGPoint direction = ccp(directionEndPoint.x-directionStartPoint.x, directionEndPoint.y-directionStartPoint.y);
    [self bezierTo:flyFlour direction:direction durTime:0.7 callback:action];
    
    /*
    [flyFlour runAction:[CCSequence actions:
                         [CCMoveTo actionWithDuration:TIMETOFLY position:realDest],
                         [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                         nil]];
     */
}
-(void)addFlyCucumber:(CGPoint)p{
    flyCucumber = [CCSprite spriteWithFile:@"fly_cucumber_2x.png" rect:CGRectMake(0, 0, FLYCUCUMBER_WIDTH, FLYCUCUMBER_HEIHT)];
    flyCucumber.scale=0.4;
    flyCucumber.tag=2;
    flyCucumber.position=p;
    [self addChild:flyCucumber z:FLY_SLICE_LAYER_Z_INDEX];
    //
    [flyCucumber runAction:[CCSequence actions:
                            [CCMoveTo actionWithDuration:TIMETOFLY position:realDest],
                            [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                            nil]];
}
-(void)addFlyMutton:(CGPoint)p{
    flyMutton = [CCSprite spriteWithFile:@"fly_mutton_2x.png" rect:CGRectMake(0, 0, FLYMUTTON_WIDTH, FLYMUTTON_HEIHT)];
    flyMutton.scale=0.4;
    flyMutton.tag=2;
    flyMutton.position=p;
    [self addChild:flyMutton z:FLY_SLICE_LAYER_Z_INDEX];
    //
    [flyMutton runAction:[CCSequence actions:
                          [CCMoveTo actionWithDuration:TIMETOFLY position:realDest],
                          [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
                          nil]];
}

-(float)getCoordinate_y:(float)x{
    float y;
    if(x>=160)
    {
        y=FOOD_Y_BOTTOM+(rightPoint_2.x-x)/(rightPoint_2.x-middlePoint.x)*(FOOD_Y_HIGH-FOOD_Y_BOTTOM);
    }
    else
    {
        y=FOOD_Y_BOTTOM+(x-leftPoint_2.x)/(middlePoint.x-leftPoint_2.x)*(FOOD_Y_HIGH-FOOD_Y_BOTTOM);
    }
    return y;
}

-(void)getAll_x:(int)index{
    if (index==BEEF_INDEX) {
        x1=temp_4.x-offset;x2=x1+distance_betweenFood;x3=x2+distance_betweenFood;x4=x3+distance_betweenFood;x5=x4+distance_betweenFood;
    }
    else if (index==RADISH_INDEX){
        x2=temp_4.x-offset;x1=x2-distance_betweenFood;x3=x2+distance_betweenFood;x4=x3+distance_betweenFood;x5=x4+distance_betweenFood;
    }
    else if (index==FLOUR_INDEX){
        x3=temp_4.x-offset;x2=x3-distance_betweenFood;x1=x2-distance_betweenFood;x4=x3+distance_betweenFood;x5=x4+distance_betweenFood;
    }
    else if(index==CUCUMBER_INDEX){
        x4=temp_4.x-offset;x3=x4-distance_betweenFood;x2=x3-distance_betweenFood;x1=x2-distance_betweenFood;x5=x4+distance_betweenFood;
    }
    else if(index==MUTTON_INDEX){
        x5=temp_4.x-offset;x4=x5-distance_betweenFood;x3=x4-distance_betweenFood;x2=x3-distance_betweenFood;x1=x2-distance_betweenFood;
    }
}

-(void)moveSprites{
    h_beef=[self getCoordinate_y:(x1)];
    Beef.position=ccp(x1,h_beef);
    h_radish=[self getCoordinate_y:(x2)];
    Radish.position=ccp(x2,h_radish);
    h_flour=[self getCoordinate_y:(x3)];
    flour.position=ccp(x3,h_flour);
    h_cucumber=[self getCoordinate_y:(x4)];
    Cucumber.position=ccp(x4,h_cucumber);
    h_mutton=[self getCoordinate_y:(x5)];
    Mutton.position=ccp(x5,h_mutton);
}

-(void)setPoints{
    leftPoint_4=ccp(winSize.width/2-distance_betweenFood*4,FOOD_Y_BOTTOM-60);
    leftPoint_3=ccp(winSize.width/2-distance_betweenFood*3,FOOD_Y_BOTTOM-30);
    leftPoint_2=ccp(winSize.width/2-distance_betweenFood*2,FOOD_Y_BOTTOM);
    leftPoint=ccp(winSize.width/2-distance_betweenFood,FOOD_Y_LOW);
    middlePoint=ccp(winSize.width/2,FOOD_Y_HIGH);
    rightPoint=ccp(winSize.width/2+distance_betweenFood,FOOD_Y_LOW);
    rightPoint_2=ccp(winSize.width/2+distance_betweenFood*2,FOOD_Y_BOTTOM);
    rightPoint_3=ccp(winSize.width/2+distance_betweenFood*3,FOOD_Y_BOTTOM-30);
    rightPoint_4=ccp(winSize.width/2+distance_betweenFood*4,FOOD_Y_BOTTOM-60);
    beefPoint=leftPoint_2;
    radishPoint=leftPoint;
    flourPoint=middlePoint;
    cucumberPoint=rightPoint;
    muttonPoint=rightPoint_2;
    _points[0]=leftPoint_4;
    _points[1]=leftPoint_3;
    _points[2]=leftPoint_2;
    _points[3]=leftPoint;
    _points[4]=middlePoint;
    _points[5]=rightPoint;
    _points[6]=rightPoint_2;
    _points[7]=rightPoint_3;
    _points[8]=rightPoint_4;
    
}

-(void)finalLocation:(int)index :(CGPoint)p{
    switch (index) {
        int a;
        case BEEF_INDEX:
        {
            a=[self theNearestPoint:p];
            beefPoint=_points[a];
            radishPoint=_points[a+1];
            flourPoint=_points[a+2];
            cucumberPoint=_points[a+3];
            muttonPoint=_points[a+4];
        
            break;
        }
        case RADISH_INDEX:
        {
            a=[self theNearestPoint:p];
            beefPoint=_points[a-1];
            radishPoint=_points[a];
            flourPoint=_points[a+1];
            cucumberPoint=_points[a+2];
            muttonPoint=_points[a+3];
            
            break;
        }
        case FLOUR_INDEX:
        {
            a=[self theNearestPoint:p];
            beefPoint=_points[a-2];
            radishPoint=_points[a-1];
            flourPoint=_points[a];
            cucumberPoint=_points[a+1];
            muttonPoint=_points[a+2];
            
            break;
        }
        case CUCUMBER_INDEX:
        {
            a=[self theNearestPoint:p];
            beefPoint=_points[a-3];
            radishPoint=_points[a-2];
            flourPoint=_points[a-1];
            cucumberPoint=_points[a];
            muttonPoint=_points[a+1];
            
            break;
        }
        case MUTTON_INDEX:
        {
            a=[self theNearestPoint:p];
            beefPoint=_points[a-4];
            radishPoint=_points[a-3];
            flourPoint=_points[a-2];
            cucumberPoint=_points[a-1];
            muttonPoint=_points[a];
            
            break;
        }
            
        default:
            break;
    }
}

-(int)foodInMiddle:(CGFloat)p_x{
    if (p_x==beefPoint.x) {
        middle_area=Beef.boundingBox;
        return BEEF_INDEX;
    }
    else if(p_x==radishPoint.x){
        middle_area=Radish.boundingBox;
        return RADISH_INDEX;
    }
    else if(p_x==flourPoint.x){
        middle_area=flour.boundingBox;
        return FLOUR_INDEX;
    }
    else if(p_x==cucumberPoint.x){
        middle_area=Cucumber.boundingBox;
        return CUCUMBER_INDEX;
    }
    else if(p_x==muttonPoint.x){
        middle_area=Mutton.boundingBox;
        return MUTTON_INDEX;
    }
}

-(int)theNearestPoint:(CGPoint)p{
    if (p.x<95) {
        return 3;
    }
    else if(95<=p.x<=255){
        return 4;
    }
    else {
        return 5;   
    }
}

-(void)moveToTheFinalLocation{
   
    [Beef runAction:[CCMoveTo actionWithDuration:TIMETODES position:beefPoint]];
    [Radish runAction:[CCMoveTo actionWithDuration:TIMETODES position:radishPoint]];
    [flour runAction:[CCMoveTo actionWithDuration:TIMETODES position:flourPoint]];
    [Cucumber runAction:[CCMoveTo actionWithDuration:TIMETODES position:cucumberPoint]];
    [Mutton runAction:[CCMoveTo actionWithDuration:TIMETODES position:muttonPoint]];
    foodIndex=[self foodInMiddle:middlePoint.x];
}

-(void)flyOneSlice:(int)index:(CGPoint)p{
    //float distance=sqrt((p.x-temp.x)*(p.x-temp.x)+(p.y-temp.y)*(p.y-temp.y));
    //CCSprite *a;
    switch (index) {
        case BEEF_INDEX:
        {
            [self addFlyBeef:p];
            break;
        }
        case RADISH_INDEX:
        {
            [self addFlyRadish:p];            
            break;
        }
        case FLOUR_INDEX:
        {
            [self addFlyFlour:p];
            break;
        }
        case CUCUMBER_INDEX:
        {
            [self addFlyCucumber:p];
            break;
        }
        case MUTTON_INDEX:
        {
            [self addFlyMutton:p];
            break;
        }
        
            
        default:
            break;
    }
}

-(void)spriteMoveFinished:(id)sender {
    CCSprite *sprite = (CCSprite *)sender;
    [self removeChild:sprite cleanup:YES];
    
    if (sprite.tag ==1) { // target
        [_targets removeObject:sprite];
        // GameOverScene *gameOverScene = [GameOverScene node];
        //[gameOverScene.layer.label setString:@"You Lose :["];
        //[[CCDirector sharedDirector] replaceScene:gameOverScene];
        //_flyFloursDestroyed=0;
    } else if (sprite.tag ==2) { // flyFlour
        
        //判断＊片是否落入当前面碗
        if([midBowl isFallIntoBowl:sprite])
        {
            [self showNumber:_numberOfFlour%10];
            _numberOfFlour++;
            int a=_numberOfFlour;
            //[_flyFlours removeObject:sprite];
            //[_flyFlours release];
            if(_numberOfFlour>0 && _numberOfFlour%10==0)
            {
                [self bowlMoveActionCallback];
                //[self reorderChild:scoreListBoardLayer z:POPPING_ITEM_Z_INDEX];
                [scoreListBoardLayer setVisible:YES];
            }
        }
    }
    else if(sprite.tag ==3)
    {
        //[_number removeObject:sprite];
    }
}

-(void)loadBgMusic{
    [[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"signal waltz.wma"];
}

-(void)playBgMusic:(NSString*)fileName{
    [[SimpleAudioEngine sharedEngine] playBackgroundMusic:fileName];
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
    [_number release];   
    _number = nil;
    [_targets release];
    _targets = nil;
    
    //[flourRect release];
    //[inside release];
    CCSprite *knife;
	[super dealloc];
}
@end
